package org.example.mylogin.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.example.mylogin.config.JwtConfig;
import org.example.mylogin.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

/**
 * @author wuyunbin
 */
@Component
public class JwtUtil {

    @Autowired
    private JwtConfig jwtConfig;
    private final Key key ;
    public JwtUtil(JwtConfig jwtConfig){
        this.jwtConfig=jwtConfig;
        key = Keys.hmacShaKeyFor(jwtConfig.getKey().getBytes());
    }

    public String createJwt(String id) {

        Claims claims = Jwts.claims();
        claims.put("id",id);

        return Jwts.builder()
                .setClaims(claims)
                //.setExpiration(new Date(System.currentTimeMillis() + jwtConfig.getTtl()))
                .signWith(key)
                .compact();
    }

    public Claims parseJwt(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public boolean validateToken(String token) {
        try {

            Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);

            return true;
        } catch (Exception e) {
            return false;
        }
    }
}

